package com.group.voting_system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.group.voting_system.entity.User;
import com.group.voting_system.entity.Vote;
import com.group.voting_system.exception.ParamNotValidException;
import com.group.voting_system.exception.RecordNotExistException;
import com.group.voting_system.mapper.CandidateMapper;
import com.group.voting_system.mapper.UserMapper;
import com.group.voting_system.mapper.VoteMapper;
import com.group.voting_system.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.group.voting_system.utils.DateUtil;
import com.group.voting_system.utils.SecureUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xyf
 * @since 2019-04-15
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    UserMapper userMapper;

    @Resource
    VoteMapper voteMapper;

    @Resource
    CandidateMapper candidateMapper;

    //辅导员票数
    @Value("${assistant}")
    Integer aVote;

    //教师票数
    @Value("${teacher}")
    Integer tVote;

    @Override
    public User getUserByJobNumAndPass(User user) throws RecordNotExistException {

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("job_number", user.getJobNumber());
        User user1 = userMapper.selectOne(wrapper);
        if (user1 == null) {
            throw new RecordNotExistException("用户不存在");
        }
        if (SecureUtil.decryptBasedDes(user1.getPassword())
                .equals(user.getPassword())) {
            user1.setPassword(null);
            return user1;
        }
        return null;
    }

    @Override
    public boolean userVote(Integer vid, Integer uid, Set<Integer> c, String ip) throws RecordNotExistException, ParamNotValidException {

        //先获取这个投票事件
        Vote vote = voteMapper.selectById(vid);

        if (vote == null) {
            throw new RecordNotExistException("该投票活动不存在");
        }

        //投票前要先判断一下用户是否违反了投票的规定
        //0.是否过了投票时间
        //1.投票次数是否达上限
        //2.每个人是不是只能投一次
        //是否支持候选人投票

        if (vote.getStartTime().after(DateUtil.getNowDate())){
            throw new ParamNotValidException("投票尚未开始");
        }

        if (vote.getEndTime().before(DateUtil.getNowDate())) {
            throw new ParamNotValidException("投票期限已过");
        }

        if (userMapper.countUserVotes(vid, uid) >= vote.getVoteLimit()) {
            throw new ParamNotValidException("一人最多投" + vote.getVoteLimit() + "票哦");
        }

        //规定辅导员一共只能投两票
        if (userMapper.countAssisVotes(vid, uid) >= aVote){
            throw new ParamNotValidException("最多可投" + aVote + "位辅导员");
        }

        //规定教师一共只能投五票
        if (userMapper.countTeacherVotes(vid, uid) >= tVote){
            throw new ParamNotValidException("最多可投" + tVote + "位教师");
        }
//        for (int i = 0; i < c.size(); i++) {
//            if (userMapper.countCandidateVotes(vid, uid, c.get(i)) >= vote.getVoteForOne()) {
//                throw new ParamNotValidException("一个候选人只能投" + vote.getVoteForOne() + "票哦");
//            }
//        }

//        List<String> list = voteMapper.getIllegalIPs();
//        for (int i = 0; i < list.size(); i++){
//            if (list.get(i).equals(ip)){
//                throw new ParamNotValidException("该IP投票次数过多！");
//            }
//        }

        Iterator<Integer> iterator = c.iterator();
        while (iterator.hasNext()) {
            if (userMapper.countCandidateVotes(vid, uid, iterator.next()) >= vote.getVoteForOne()){
                throw new ParamNotValidException("一个候选人只能投" + vote.getVoteForOne() + "票哦");
            }
        }

        //判断一下是否带候选人投票
        if (vote.getIsSelfVoted()) {
            if (candidateMapper.isCandidate(uid, vid)) {
                throw new ParamNotValidException("候选人不可以投票哦");
            }
        }

        //开始投票
        return userMapper.vote(vote, uid, c, DateUtil.getNowDate(), ip);
    }

    @Override
    public IPage<User> selectAllUsers(Page<User> page) {

        IPage<User> allUsers = userMapper.getAllUsers(page);

        return allUsers;
    }

    @Override
    public IPage<User> pageUserNotCandidate(Page<User> page, Integer vid, User condition) {
        IPage<User> iPage = userMapper.pageUserNotCandidate(page, vid, condition);
        return iPage;
    }

    @Override
    public User existYibanUser(String userid) {
        return userMapper.getYibanUserByJobNumber(userid);
    }
}